$dir = "/data2/bsi/RandD/bora/METHYLATION/methylation_result";
$names = `ls $dir`;
#values to be changed
$val1 = "9";
$val2 = "BETA_VALUE";

#values to be changed for signal A
$val1 = "6";
$val2 = "METHYLATED";

#values to be changed for signal B
$val1 = "7";
$val2 = "UNMETHYLATED";

#print $dir."\n";
@dir = split("\n",$names);
$m = 0;
for($i=0;$i<@dir;$i++)
{
	print "processing $dir[$i]\n";
	$n =0;
	$subdir = `ls $dir/$dir[$i]`;
	@tissue = split(/_|\./,$dir[$i]);
	$tissue = $tissue[2];
	#print $tissue[2]."\n";
	#print $subdir."\n";
	@subdir = split("\n",$subdir);
	@filenames=();
	for($j=0;$j<@subdir;$j++)
	{
		#@filenames=();
		if($subdir[$j]  ne "sample.error" && $subdir[$j]  ne "sample.qc" && $subdir[$j]  ne "merged_beta2.txt" && $subdir[$j]  ne "merged_beta.txt" && $subdir[$j]  ne "merged_beta1.txt")
		{
			#print "$dir/$dir[$i]/$subdir[$j]\n";
			$filename = "$tissue-$subdir[$j]";
			$filename =~ s/\.NORM//g;	
			#print $filename."\n";
			@id = split("-",$filename);
			push(@filenames,[$id[0],$id[1],$id[2],$id[3],$id[4],$id[5],$id[6],$id[7]]);
		}
	}
	#print @filenames[0]."\n";
	@file_array = sort {$a->[0] cmp $b->[0] || $a->[4] cmp $b->[4] || $a->[7] cmp $b->[7] || $a->[6] cmp $b->[6]} @filenames;
	foreach (@file_array)
	{
		#print $$_[0]."\t".$$_[1]."\n";
		$colname = join("-",@$_);
		$file ="$dir/$dir[$i]/$$_[1]-$$_[2]-$$_[3]-$$_[4]-$$_[5]-$$_[6]-$$_[7].NORM";
		
		#open(BUFF,"$dir/$dir[$i]/
		print $colname."\t$file\n";
		if($n ==0)
		{
			$n++;
			if($m ==0)
			{
				system("cut -f5 $file> $dir/../merged_beta.txt");
				$m++
			}
			system("cut -f$val1 $file> $dir/$dir[$i]/merged_beta.txt");
			system("sed 's/$val2/$colname/' $dir/$dir[$i]/merged_beta.txt > $dir/$dir[$i]/merged_beta1.txt");
			system("mv $dir/$dir[$i]/merged_beta1.txt $dir/$dir[$i]/merged_beta.txt");
		}
		else
		{
			system("cut -f$val1 $file> $dir/$dir[$i]/merged_beta1.txt");
			system("sed 's/$val2/$colname/' $dir/$dir[$i]/merged_beta1.txt > $dir/$dir[$i]/merged_beta2.txt");
			system("paste $dir/$dir[$i]/merged_beta.txt $dir/$dir[$i]/merged_beta2.txt > $dir/$dir[$i]/merged_beta1.txt");
			system("mv $dir/$dir[$i]/merged_beta1.txt $dir/$dir[$i]/merged_beta.txt");
			system("rm $dir/$dir[$i]/merged_beta2.txt");
		}
	}
	#print "@$_\n" foreach ( @snpsHash );
	#die;
}
print "merging all files\n";
for($i=0;$i<@dir;$i++)
{
		system("paste $dir/../merged_beta.txt $dir/$dir[$i]/merged_beta.txt > $dir/../merged_beta1.txt");
		system("mv $dir/../merged_beta1.txt $dir/../merged_beta.txt");
		
}	
